package com.rfsp.mcp.service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.rfsp.common.pojo.vo.DictVO;
import com.rfsp.common.service.AreaService;
import com.rfsp.common.util.DateUtil;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.enums.McpConst;
import com.rfsp.mcp.enums.MiPayDataTypeEnum;
import com.rfsp.mcp.mapper.CustOrgTypeMapper;
import com.rfsp.mcp.pojo.dto.MiPayLogDTO;

import com.rfsp.mcp.pojo.po.CustOrgTypePO;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.sdto.PfmSDTO;
import com.rfsp.mcp.pojo.vo.HospitalYBDPdfVO;
import com.rfsp.mcp.pojo.vo.MiAccountVO;
import com.rfsp.mcp.pojo.vo.PfmVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.BaseService;
import com.rfsp.mcp.mapper.MiPayLogMapper;
import com.rfsp.mcp.pojo.po.MiPayLogPO;
import com.rfsp.mcp.pojo.sdto.MiPayLogSDTO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.mcp.pojo.vo.MiPayLogVO;

import javax.annotation.PostConstruct;

@Service
public class PayLogService extends BaseService<MiPayLogPO> {

    private static Map<String, String> queryReasonTypeMap = new ConcurrentHashMap<>();
    private static Map<String, String> validFlagMap = new ConcurrentHashMap<>();

    @Autowired
    MiPayLogMapper miPayLogMapper;

    @Autowired
    SystemCodeService systemCodeService;

    @Autowired
    private CustOrgTypeMapper custOrgTypeMapper;

    @Autowired
    private AreaService areaService;

    @PostConstruct
    public void init() {
        //查询原因类型：1交易前调查、2交易中监测、3交易后管理、4破产事务管理、5业务纠纷、6其他合法目的
        queryReasonTypeMap.put("1", "交易前调查");
        queryReasonTypeMap.put("2", "交易中监测");
        queryReasonTypeMap.put("3", "交易后管理");
        queryReasonTypeMap.put("4", "破产事务管理");
        queryReasonTypeMap.put("5", "业务纠纷");
        queryReasonTypeMap.put("6", "其他合法目的");

        validFlagMap.put("1", "有效");
        validFlagMap.put("0", "无效");
    }

	public PageInfo<MiPayLogVO> get(MiPayLogSDTO sdto, PageSDTO pageSdto){
        if(pageSdto!=null){
            PageHelper.startPage(pageSdto.getPageNum(), pageSdto.getPageSize());
        }
        List<MiPayLogVO> voList = miPayLogMapper.get(sdto);
        PageInfo<MiPayLogVO> page = new PageInfo(voList);
        return page;
    }
    public List<MiPayLogVO> get(MiPayLogSDTO sdto){
        List<MiPayLogVO> voList = miPayLogMapper.get(sdto);
        return voList;
    }
	public MiPayLogVO getById(Long id){
        MiPayLogPO po=this.get(id);
        MiPayLogVO vo=new MiPayLogVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }
	public PageInfo<MiPayLogVO> getByAuthId(Long authId, PageSDTO pageSdto){
        if(pageSdto!=null){
            PageHelper.startPage(pageSdto.getPageNum(), pageSdto.getPageSize());
        }
        
        List<MiPayLogVO> voList = miPayLogMapper.selectVOByAuthId(authId);
        combo(voList);
        
        PageInfo<MiPayLogVO> page = new PageInfo(voList);
        return page;
    }

    /**
     * 保存结算信息记录
     * @param dto   结算数据
     * @param map   次数限制
     * @return
     */
    public Integer saveMiPayLog(MiPayLogDTO dto, Map<String, Boolean> map){
        if (StringUtils.isBlank(dto.getQueryReason()) && StringUtils.isNotBlank(dto.getQueryReasonType())) {
            dto.setQueryReason(queryReasonTypeMap.get(dto.getQueryReasonType()));
        }
        if (StringUtils.isNotBlank(dto.getQueryReason()) && StringUtils.isNotBlank(dto.getQueryReasonType()) && "6".equals(dto.getQueryReasonType())) {
            dto.setQueryReason(queryReasonTypeMap.get(dto.getQueryReasonType()) + "-" + dto.getQueryReason());
        }
	    dto.setAid(this.getAID());
        dto.setQueryTime(new Date());
        dto.setOptTime(new Date());
        dto.setState("1");

	    MiPayLogPO e=new MiPayLogPO();
        BeanUtils.copyProperties(dto,e);
        //默认值为0
        e.setDataType1("0");
        e.setDataType2("0");
        e.setDataType3("0");
        if(StringUtils.isNotBlank(dto.getDataType()) && map != null && !map.isEmpty()) {
        	String dataType = dto.getDataType();
        	if(dataType.indexOf("1") != -1 && !map.get(MiPayDataTypeEnum.MI_MAIN.getKey())) {
        		e.setDataType1("1");
        	}
        	if(dataType.indexOf("2") != -1 && !map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey())) {
        		e.setDataType2("1");
        	}
        	if(dataType.indexOf("3") != -1 && !map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
        		e.setDataType3("1");
        	}

            if(StringUtils.isNotBlank(dto.getItfType())) {
                if("0".equals(dto.getItfType())) {
                    //宿迁
                    if ("1".equals(e.getDataType3())) {
                        //PL
                        e.setPayLogCode(systemCodeService.getBussCode("payLog"));
                    }
                }else {
                    //抚顺
                    if ("1".equals(e.getDataType1()) && !map.get(MiPayDataTypeEnum.MI_MAIN.getKey())) {
                        //GREG
                        e.setPayLogCode(systemCodeService.getBussCode("mi-pfm"));
                    }
                    if ("1".equals(e.getDataType2()) || "1".equals(e.getDataType3())) {
                        //GPL
                        if ("1".equals(e.getDataType2()) && !"1".equals(e.getDataType3()) && !map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey())) {
                            if (StringUtils.isNotBlank(e.getPayLogCode())) {
                                e.setPayLogCode(e.getPayLogCode() + "," + systemCodeService.getBussCode("payLog-pfm"));
                            }else {
                                e.setPayLogCode(systemCodeService.getBussCode("payLog-pfm"));
                            }
                        }else if (!"1".equals(e.getDataType2()) && "1".equals(e.getDataType3()) && !map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
                            if (StringUtils.isNotBlank(e.getPayLogCode())) {
                                e.setPayLogCode(e.getPayLogCode() + "," + systemCodeService.getBussCode("payLog-pfm"));
                            }else {
                                e.setPayLogCode(systemCodeService.getBussCode("payLog-pfm"));
                            }
                        }else {
                            if (!map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey()) && !map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
                                if (StringUtils.isNotBlank(e.getPayLogCode())) {
                                    e.setPayLogCode(e.getPayLogCode() + "," + systemCodeService.getBussCode("payLog-pfm"));
                                }else {
                                    e.setPayLogCode(systemCodeService.getBussCode("payLog-pfm"));
                                }
                            }
                        }
                    }
                }
            }else {
                //PL
                e.setPayLogCode(systemCodeService.getBussCode("payLog"));
            }
        }else {
            //宿迁给dataType默认值
            e.setDataType3("1");
            //PL
            e.setPayLogCode(systemCodeService.getBussCode("payLog"));
        }
        
        if(StringUtils.isNotBlank(dto.getPayStartDate())) {
        	e.setPayStartDate(DateUtil.parseDateByYYYYMMDD(dto.getPayStartDate()));
        }
        if(StringUtils.isNotBlank(dto.getPayEndDate())) {
        	e.setPayEndDate(DateUtil.parseDateByYYYYMMDD(dto.getPayEndDate()));
        }
        
        Integer count=this.save(e);
        dto.setId(e.getId());
        return count;
    }
    public Integer updateById(Long id,MiPayLogDTO dto){
	    dto.setId(id);
        MiPayLogPO e=new MiPayLogPO();
        BeanUtils.copyProperties(dto,e);
	    return this.update(e);
    }
    public Integer deleteById(Long id){
        return mapper.deleteByPrimaryKey(id);
    }
	public void combo(MiPayLogVO vo){
    	
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	
    	vo.setQueryTimeStr(sdf.format(vo.getQueryTime()));
//    	vo.setQueryPayStateName("查询失败");
//    	if("1".equals(vo.getQueryPayState())){
//            vo.setQueryPayStateName("查询成功");
//        }
        if (StringUtils.isNotBlank(vo.getPayLogCode())) {
            List<String> payLogCodes = getPayLogCodes(vo.getPayLogCode());
            if (payLogCodes.size() > 1) {
                if ("0".equals(vo.getDataType1()) && ("1".equals(vo.getDataType2()) || "1".equals(vo.getDataType3()))) {
                    List<String> list = new ArrayList<>();
                    list.add(payLogCodes.get(1));
                    vo.setPayLogCodes(list);
                } else {
                    vo.setPayLogCodes(payLogCodes);
                }
            }else {
                vo.setPayLogCodes(payLogCodes);
            }
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -5);
        Date date=calendar.getTime();
        vo.setDownloadEnabled("0");
    	if(date.compareTo(vo.getQueryTime())<0){
            vo.setDownloadEnabled("1");
        }
//        if (StringUtils.isBlank(vo.getQueryReason()) && StringUtils.isNotBlank(vo.getQueryReasonType())) {
//            vo.setQueryReason(queryReasonTypeMap.get(vo.getQueryReasonType()));
//        }
//        if (StringUtils.isNotBlank(vo.getQueryReason()) && StringUtils.isNotBlank(vo.getQueryReasonType()) && "6".equals(vo.getQueryReasonType())) {
//            vo.setQueryReason(queryReasonTypeMap.get(vo.getQueryReasonType()) + "-" + vo.getQueryReason());
//        }
    }

    public List<String> getPayLogCodes(String payLogCode) {
        if (payLogCode == null || payLogCode.trim().isEmpty()) {
            return Collections.emptyList();
        }
        return Arrays.stream(payLogCode.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }

    public void combo(List<MiPayLogVO> voList){
        for(MiPayLogVO vo:voList ){
            combo(XssUtils.replaceUnXss(vo));
        }
    }

    /**
     * 获取主体信息查询成功次数
     * @param startDate
     * @param endDate
     * @return
     */
    public Integer getZTSearchSuccessCount(String startDate, String endDate, Long queryOrgId, Long targetOrgId, Long orgYbjId) {
        return miPayLogMapper.getZTSearchSuccessCount(startDate, endDate, queryOrgId, targetOrgId, orgYbjId);
    }

    /**
     * 获取医保账户信息查询成功次数
     * @param startDate
     * @param endDate
     * @return
     */
    public Integer getYBZHSearchSuccessCount(String startDate, String endDate, Long queryOrgId, Long targetOrgId, Long orgYbjId) {
        return miPayLogMapper.getYBZHSearchSuccessCount(startDate, endDate, queryOrgId, targetOrgId, orgYbjId);
    }

    /**
     * 获取结算明细查询成功次数
     * @param startDate
     * @param endDate
     * @return
     */
    public Integer getJSMXSearchSuccessCount(String startDate, String endDate, Long queryOrgId, Long targetOrgId, Long orgYbjId) {
        return miPayLogMapper.getJSMXSearchSuccessCount(startDate, endDate, queryOrgId, targetOrgId, orgYbjId);
    }

    public String getLDJGCountLimit() {
        return miPayLogMapper.getLDJGCountLimit();
    }

    public String getZJFCountLimit() {
        return miPayLogMapper.getZJFCountLimit();
    }

    public List<DictVO> getPlatDict(PfmService pfmService){
        List<PfmVO> list = pfmService.get(new PfmSDTO());
        List<DictVO> dictList = new ArrayList<>();
        if (null != list && !list.isEmpty()) {
            list.forEach(vo -> dictList.add(new DictVO(String.valueOf(vo.getId()), vo.getPfmName())));
        }
        return dictList;
    }

    public MiAccountVO findMiAccountVOByPayLogId(Long id) {
        return miPayLogMapper.findMiAccountVOByPayLogId(id);
    }

    public HospitalYBDPdfVO coverYBDPdfVO(OrgPO org, OrgYbjPO orgYbj, Date queryTime, String dataSource) {


        HospitalYBDPdfVO pdfYBDVO = new HospitalYBDPdfVO();
        pdfYBDVO.setDate(DateUtil.Date2String(queryTime,DateUtil.DEFAULT_TIME_FMT5,null));

        /*平台注册信息*/
        pdfYBDVO.setOrgName(org.getOrgName());
        pdfYBDVO.setOrgCode(org.getOrgCode());
        pdfYBDVO.setCorporation(org.getCorporation());

        String enterpriseType = "";
        CustOrgTypePO custOrgTypePO = null;
        if(StringUtils.isNotBlank(org.getOrgType())) {
            if(org.getOrgType().length() == 2) {
                custOrgTypePO = custOrgTypeMapper.get(org.getOrgType());
                if(custOrgTypePO != null) {
                    enterpriseType = custOrgTypePO.getOrgname();
                }
            }else {
                String orgType1 = "";
                String orgType2 = "";
                custOrgTypePO = custOrgTypeMapper.get(org.getOrgType().substring(0, 2));
                if(custOrgTypePO != null) {
                    orgType1 = custOrgTypePO.getOrgname();

                    custOrgTypePO = custOrgTypeMapper.get(org.getOrgType());
                    if(custOrgTypePO != null) {
                        orgType2 = custOrgTypePO.getOrgname();
                        enterpriseType = orgType1 + "-" +orgType2;
                    }
                }
            }
        }
        pdfYBDVO.setEnterpriseType(enterpriseType);

        String orgAreaCode = StringUtils.isBlank(org.getCounty())?(StringUtils.isBlank(org.getCity())?org.getProvince():org.getCity()):org.getCounty();
        pdfYBDVO.setOrgAddress(areaService.getFullAddress(orgAreaCode).replace("-", "")+org.getAddress());
        pdfYBDVO.setSource(dataSource);
        /******政务共享信息******/
        if (orgYbj != null) {
            /* 一、基本信息 */
            pdfYBDVO.setOrgNameYbj(StringUtils.isNotBlank(orgYbj.getOrgName()) ? orgYbj.getOrgName() : "");
            pdfYBDVO.setOrgCodeYbj(StringUtils.isNotBlank(orgYbj.getOrgCode()) ? orgYbj.getOrgCode() : "");
            pdfYBDVO.setOrgNo(StringUtils.isNotBlank(orgYbj.getOrgNo()) ? orgYbj.getOrgNo() : "");
            pdfYBDVO.setComName(StringUtils.isNotBlank(orgYbj.getCorporation()) ? orgYbj.getCorporation() : "");
            pdfYBDVO.setDirector(StringUtils.isNotBlank(orgYbj.getDirector()) ? orgYbj.getDirector() : "");
            pdfYBDVO.setYbjAddress(StringUtils.isNotBlank(orgYbj.getAddress()) ? orgYbj.getAddress() : "");
            pdfYBDVO.setEconomicType(StringUtils.isNotBlank(orgYbj.getEconomicType()) ? orgYbj.getEconomicType() : "");
            pdfYBDVO.setBizNature(StringUtils.isNotBlank(orgYbj.getBizNature()) ? orgYbj.getBizNature() : "");
            pdfYBDVO.setAffiliation(StringUtils.isNotBlank(orgYbj.getAffiliation()) ? orgYbj.getAffiliation() : "");
            pdfYBDVO.setOrgType(StringUtils.isNotBlank(orgYbj.getOrgType()) ? (StringUtils.isNotBlank(McpConst.YbjOrgTypeDict.getVal(orgYbj.getOrgType())) ? McpConst.YbjOrgTypeDict.getVal(orgYbj.getOrgType()) : orgYbj.getOrgType()) : "");
            pdfYBDVO.setBedNum(StringUtils.isNotBlank(orgYbj.getBedNum()) ? orgYbj.getBedNum() : "");
            pdfYBDVO.setOrgClass(StringUtils.isNotBlank(orgYbj.getOrgClass()) ? (StringUtils.isNotBlank(McpConst.YbjOrgClassDict.getVal(orgYbj.getOrgClass())) ? McpConst.YbjOrgClassDict.getVal(orgYbj.getOrgClass()) : orgYbj.getOrgClass()) : "");
            pdfYBDVO.setFeeLevel(StringUtils.isNotBlank(orgYbj.getFeeLevel()) ? orgYbj.getFeeLevel() : "");
            pdfYBDVO.setOrgGrade(StringUtils.isNotBlank(orgYbj.getOrgGrade()) ? orgYbj.getOrgGrade() : "");
            pdfYBDVO.setBizSubject(StringUtils.isNotBlank(orgYbj.getBizSubject()) ? orgYbj.getBizSubject() : "");
            pdfYBDVO.setProLicenseNo(StringUtils.isNotBlank(orgYbj.getProLicenseNo()) ? orgYbj.getProLicenseNo() : "");
            pdfYBDVO.setProlicNoTimeLimit(StringUtils.isNotBlank(orgYbj.getProlicnoTimelimit()) ? orgYbj.getProlicnoTimelimit() : "");

            /*二、医保服务协议信息*/
            pdfYBDVO.setApproveTime(StringUtils.isNotBlank(orgYbj.getApproveTime()) ? orgYbj.getApproveTime() : "");
            pdfYBDVO.setApproveNo(StringUtils.isNotBlank(orgYbj.getApproveNo()) ? orgYbj.getApproveNo() : "");
            pdfYBDVO.setValidFlag(StringUtils.isNotBlank(orgYbj.getValidFlag()) ? (StringUtils.isNotBlank(validFlagMap.get(orgYbj.getValidFlag())) ? validFlagMap.get(orgYbj.getValidFlag()) : orgYbj.getValidFlag()) : "");
            pdfYBDVO.setBizArea(StringUtils.isNotBlank(orgYbj.getBizArea()) ? areaService.getFullAddress(orgYbj.getBizArea()) : "");
            if (orgYbj.getValidStartDate() != null) {
                pdfYBDVO.setValidStartDate(orgYbj.getValidStartDate());
            }
            if (orgYbj.getValidEndDate() != null) {
                pdfYBDVO.setValidEndDate(orgYbj.getValidEndDate());
            }
            pdfYBDVO.setMiGrade(StringUtils.isNotBlank(orgYbj.getMiGrade()) ? orgYbj.getMiGrade() : "");
            pdfYBDVO.setPayType(StringUtils.isNotBlank(orgYbj.getPayType()) ? orgYbj.getPayType() : "");
        }

        return pdfYBDVO;
    }

    public MiPayLogVO findLastOne(MiPayLogVO miPayLogVO) {
        return miPayLogMapper.findLastOne(miPayLogVO);
    }
}
